package com.cjx.print;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;

import com.cjx.print.entity.MaterialEntity;
import com.cjx.print.entity.OrderWrap;
import com.cjx.print.helper.BluetoothHelper;
import com.cjx.print.helper.JCPrinterHelper;
import com.cjx.print.helper.XYPrinterHelper;
import com.cjx.print.helper.XYPrinterHelperOld;
import com.cjx.print.utils.LogUtil;
import com.cjx.print.utils.SPUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.List;

/**
 * Created by bpb on 2020-04-09.
 * 说明：am start-service -n com.cjx.print/com.cjx.print.BackgroundService
 */
public class BackgroundServiceOld extends Service {
    private static final int NOTIFICATION_ID = 10;
    private static final String CHANNEL_ID = "print_channel";
    public static final String ACTION_PRINT_TAG = "CJX.PRINT_TAG";

    public static final int MODE_FORMULA = 1; // 打印商品配方
    public static final int MODE_ORDER = 2; // 打印订单
    public static final int MODE_MATERIAL = 3; // 打印物料标签

    public static final String DATA_JSON = "DATA_JSON";
    public static final String DATA_TYPE = "DATA_TYPE";


    private int currentMode;
    private int currentType;

    private BluetoothHelper bluetoothHelper;
    private JCPrinterHelper jcPrinterHelper;
    private XYPrinterHelperOld xyPrinterHelper;

    private boolean connectStatus = false;

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                int mode = intent.getIntExtra(DATA_TYPE, 0);
                String json = intent.getStringExtra(DATA_JSON);
                LogUtil.getInstance().log("SERVER", "收到信息 " + ACTION_PRINT_TAG + " mode: " + mode + ", json: " + json);

                switch (mode) {
                    case MODE_ORDER:
                        OrderWrap orderWrap = new Gson().fromJson(json, new TypeToken<OrderWrap>() {
                        }.getType());
                        if (currentMode == 0) {
                            jcPrinterHelper.printOrderLabel(orderWrap.serialNumber, orderWrap.time, orderWrap.goodsList);
                        } else if (currentMode == 1) {
                            xyPrinterHelper.printOrderLabel(orderWrap.time, orderWrap.goodsList);
                        }
                        break;
                    case MODE_MATERIAL:
                        MaterialEntity material = new Gson().fromJson(json, new TypeToken<MaterialEntity>() {
                        }.getType());
                        if (currentMode == 0) {
                            jcPrinterHelper.printMaterialTag(material);
                        }
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private final Handler protectHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            protectHandler.removeMessages(0);
            protectHandler.sendEmptyMessageDelayed(0, 5000);
            Intent intent = new Intent(App.ACTION_PRINTER_CONNECT_STATUS);
            intent.putExtra("status", connectStatus);
            sendBroadcast(intent);

            return false;
        }
    });

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.getInstance().initLogFile(this, Constants.FILE_LOG_RUN_DIR);
        LogUtil.getInstance().log("打印服务", "创建了服务");
        // 如果是 Android 8.0 及以上，必须创建前台服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(NOTIFICATION_ID, buildNotification());
        }
        try {
            unregisterReceiver(receiver);
        } catch (Exception ignore) {
        }
        registerReceiver(receiver, new IntentFilter(ACTION_PRINT_TAG));

        protectHandler.sendEmptyMessageDelayed(0, 5000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (connectStatus) {
            // 断开连接
            disconnect();
            connectStatus = false;
        }
        if (intent != null && intent.hasExtra("type") && intent.hasExtra("mode")) {
            currentMode = intent.getIntExtra("mode", 1);
            currentType = intent.getIntExtra("type", 1);
        } else {
            currentMode = SPUtils.getInt(App.SP_MODE, 1);
            currentType = SPUtils.getInt(App.SP_TYPE, 1);
        }
        connect();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        LogUtil.getInstance().log("SERVER", "销毁服务");
    }


    private Notification buildNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "YL-Print",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("YL-Print")
                .setContentText("Running")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build();
    }

    private void disconnect() {
        if (currentMode == 0) {
            JCPrinterHelper.getInstance().disconnect();
        } else {
            XYPrinterHelperOld.getInstance().closeDevice();
        }
    }

    private void connect() {
        new Thread() {
            @Override
            public void run() {
                if (currentMode == 0) { // 精臣打印机， 只支持蓝牙
                    startJCPrinter();
                } else if (currentMode == 1) {
                    if (currentType == 0) {
                        startXYPrinterBluetooth();
                    } else {
                        startXYPrinterUSB();
                    }
                }
            }
        }.start();
    }

    private void startJCPrinter() {
        bluetoothHelper = BluetoothHelper.getInstance();
        jcPrinterHelper = JCPrinterHelper.getInstance();
        if (bluetoothHelper.openBluetooth()) {
            bluetoothHelper.setDeviceHandlerCallback(d -> {
                if (d == null) {
                    System.out.println("---------------结束了 连接状态：" + connectStatus);
                    if (!connectStatus) {
                        bluetoothHelper.startScan();
                    }
                    return;
                }
                String deviceName = d.getName();
                if (d.getType() == 1 && deviceName != null && (deviceName.startsWith("B3S-") || deviceName.startsWith("B3S_P-"))) {
                    System.out.println("识别到设备 " + d.getName() + ", " + d.getAddress() + ", " + d.getType() + ", " + new Gson().toJson(d.getBluetoothClass()));
                    bluetoothHelper.stopScan();
                    jcPrinterHelper.connectDevice(d.getAddress(), 1000, success -> {
                        connectStatus = success;
                        LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
                    });
                }
            });
            bluetoothHelper.startScan();
        }
    }

    private void startXYPrinterBluetooth() {
        bluetoothHelper = BluetoothHelper.getInstance();
        xyPrinterHelper = XYPrinterHelperOld.getInstance();
        if (bluetoothHelper.openBluetooth()) {
            bluetoothHelper.setDeviceHandlerCallback(d -> {
                if (d == null) {
                    System.out.println("---------------结束了 连接状态：" + connectStatus);
                    if (!connectStatus) {
                        bluetoothHelper.startScan();
                    }
                    return;
                }
                String deviceName = d.getName();
                if (d.getType() == 1 && deviceName != null && deviceName.equals("XP-T271U")) {
                    System.out.println("识别到设备 " + d.getName() + ", " + d.getAddress() + ", " + d.getType() + ", " + new Gson().toJson(d.getBluetoothClass()));
                    bluetoothHelper.stopScan();
                    xyPrinterHelper.connectBluetooth(d.getAddress(), success -> {
                        connectStatus = success;
                        LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
                    });
                }
            });
            bluetoothHelper.startScan();
        }
    }

    private void startXYPrinterUSB() {
        xyPrinterHelper = XYPrinterHelperOld.getInstance();
        List<String> usbDevices = xyPrinterHelper.getUsbDevices();
        System.out.println("USB 端口：" + new Gson().toJson(usbDevices));
        if (!usbDevices.isEmpty()) {
            xyPrinterHelper.connectUSB(usbDevices.get(0), success -> {
                connectStatus = success;
                LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(success);
            });
        } else {
            LiveEventBus.get(App.BUS_CONNECT, Boolean.class).post(false);
        }
    }
}
